import apiClient, { wrapApiCall } from './api';
import type {
  ApiResponse,
} from '../types/api';

// 控制台管理API服务
export const consoleService = {
  // 获取VNC连接信息
  getVNCInfo: async (connectionId: string, vmName: string): Promise<any> => {
    const response = await wrapApiCall<any>(apiClient.get('/console/vnc/info', {
      params: { connection: connectionId, name: vmName }
    }));
    return response;
  },

  // 获取SPICE连接信息
  getSPICEInfo: async (connectionId: string, vmName: string): Promise<any> => {
    const response = await wrapApiCall<any>(apiClient.get('/console/spice/info', {
      params: { connection: connectionId, name: vmName }
    }));
    return response;
  },

  // 获取串行控制台连接信息
  getSerialInfo: async (connectionId: string, vmName: string): Promise<any> => {
    const response = await wrapApiCall<any>(apiClient.get('/console/serial/info', {
      params: { connection: connectionId, name: vmName }
    }));
    return response;
  },

  // 关闭所有串口会话
  closeSerialSessions: async (connectionId: string, vmName: string): Promise<void> => {
    await wrapApiCall<ApiResponse>(apiClient.delete('/console/serial/sessions', {
      params: { connection: connectionId, name: vmName }
    }));
  },

  // 获取控制台WebSocket URL
  getConsoleURL: async (connectionId: string, vmName: string, consoleType: string): Promise<string> => {
    const response = await wrapApiCall<ApiResponse>(apiClient.get('/console/url', {
      params: { connection: connectionId, name: vmName, type: consoleType }
    }));
    return response.data as string;
  },

  // 获取可用的控制台类型
  getConsoleTypes: async (connectionId: string, vmName: string): Promise<string[]> => {
    const response = await wrapApiCall<ApiResponse>(apiClient.get('/console/types', {
      params: { connection: connectionId, name: vmName }
    }));
    return response.data as string[];
  },
  
  // 获取控制台信息
  getConsoleInfo: async (connectionId: string, vmName: string): Promise<any> => {
    const response = await wrapApiCall<ApiResponse>(apiClient.get('/console/info', {
      params: { connection: connectionId, name: vmName }
    }));
    return response;
  },
};

// WebSocket控制台客户端Hook
export interface UseConsoleWebSocketProps {
  onOpen?: () => void;
  onClose?: () => void;
  onError?: (error: Event) => void;
  onMessage?: (data: string | ArrayBuffer) => void;
}

export interface UseConsoleWebSocketReturn {
  connect: (url: string) => void;
  disconnect: () => void;
  send: (data: string | ArrayBufferLike) => void;
  isConnected: boolean;
  isConnecting: boolean;
}

export const useConsoleWebSocket = (props?: UseConsoleWebSocketProps): UseConsoleWebSocketReturn => {
  const { onOpen, onClose, onError, onMessage } = props || {};
  
  let websocket: WebSocket | null = null;
  let connected = false;
  let connecting = false;
  
  const connect = (url: string) => {
    if (connected || connecting) {
      console.warn('WebSocket is already connected or connecting');
      return;
    }
    
    try {
      connecting = true;
      websocket = new WebSocket(url);
      
      websocket.onopen = () => {
        connecting = false;
        connected = true;
        console.log('WebSocket connected to:', url);
        onOpen?.();
      };
      
      websocket.onclose = () => {
        connecting = false;
        connected = false;
        console.log('WebSocket disconnected from:', url);
        onClose?.();
      };
      
      websocket.onerror = (error) => {
        connecting = false;
        connected = false;
        console.error('WebSocket error:', error);
        onError?.(error);
      };
      
      websocket.onmessage = (event) => {
        onMessage?.(event.data);
      };
    } catch (error) {
      connecting = false;
      connected = false;
      console.error('Failed to create WebSocket connection:', error);
      onError?.(error as Event);
    }
  };
  
  const disconnect = () => {
    if (websocket) {
      websocket.close();
      websocket = null;
    }
    connected = false;
    connecting = false;
  };
  
  const send = (data: string | ArrayBufferLike) => {
    if (websocket && connected) {
      websocket.send(data);
    } else {
      console.warn('WebSocket is not connected. Cannot send data.');
    }
  };
  
  return {
    connect,
    disconnect,
    send,
    isConnected: connected,
    isConnecting: connecting
  };
};